package com.ita.service;

import com.ita.core.CustomerListFactory;
import com.ita.dataset.DoubleLinkedList;
import com.ita.entity.Customer;

/***
 * Customer business service
 * @author Elvis
 *
 */
public class CustomerService {

	private DoubleLinkedList<Customer> clist;

	public CustomerService() {
		clist = CustomerListFactory.getInstance();
	}

	public void addCustomer(Customer c) {

		clist.add(c, 0);

	}

	public Customer[] findAllCustomer() {

		return listToArr(clist);

	}

	public Customer[] findById(String id) {

		Customer[] customers = new Customer[1];
		for (int i = 0; i < clist.listLength(); i++) {
			Customer c = clist.get(i);
			if (c.getId().toUpperCase().equals(id)) {
				customers[0] = c;
				return customers;
			}

		}
		return null;

	}

	public Customer[] findByNameAndSex(String name, String sex) {

		Customer[] customers = new Customer[1];
		for (int i = 0; i < clist.listLength(); i++) {
			Customer c = clist.get(i);
			if (c.getName().toUpperCase().equals(name) && c.getSex().toUpperCase().equals(sex)) {
				customers[0] = c;
				return customers;
			}

		}
		return null;

	}

	public static Customer[] listToArr(DoubleLinkedList<Customer> list) {

		Customer[] cArr = new Customer[list.listLength()];
		for (int i = 0; i < cArr.length; i++) {
			cArr[i] = list.get(i);
		}
		return cArr;
	}

	public void updateCustomer(Customer c) {

	}

	public void delAndModCustomer(Customer c, Customer newC) {

		for (int i = 0; i < clist.listLength(); i++) {
			Customer c1 = clist.get(i);
			if (c.getId().equals(c1.getId())) {
				clist.remove(i);
				clist.add(newC, i);
			}

		}
	}

	public void deleteCustomer(String id) {

		Customer c = findById(id)[0];
		for (int i = 0; i < clist.listLength(); i++) {
			Customer c1 = clist.get(i);
			if (c.getId().equals(c1.getId())) {
				clist.remove(i);
			}

		}
	}

	public Customer[] find(String condtion) {
		return null;
	}

	public Customer[] sort() {

		Customer[] cArr = listToArr(clist);
		for (int i = 0; i < cArr.length - 1; i++) {
			for (int j = i + 1; j < cArr.length; j++) {
				if (Integer.parseInt(cArr[i].getId()) > Integer.parseInt(cArr[j].getId())) {
					Customer c = cArr[i];
					cArr[i] = cArr[j];
					cArr[j] = c;
				}
			}
		}
		return cArr;
	}

}
